import compileTemplate from './compile';

//模板池
const domNodePool = [];

export function createApp(options) {
  // console.log(options);
  /**
   * {
   *   components: [ƒ, ƒ]
   * }
   */

  for (let option in options) {
    // console.log(option);
    //components

    switch (option) {
      case 'components':
        //options[option] -> components
        initComponent(options[option]);
        break;
      default:
        break;
    }
  }

  return {
    mount: mount
  }
}

//初始组件
function initComponent(components) {
  // console.log(components);
  //[ƒ, ƒ]
  for (let component of components) {
    let [template, state] = component();
    // console.log(template, state);
    //打印的是 模板 和 响应化之后的Proxy数据

    //根据响应式数据编译{}/{{}}数据的模板并替换成新的node节点
    const node = compileTemplate(template, state);
    // console.log(node); -> 替换好模板的 <ul class="list">...</ul>

    //将所有替换好的节点插入到模板池里
    domNodePool.push(node);

  }
}

function mount(el) {
  const app = document.querySelector(el);
  // console.log(app);
  // <div id="app"></div>

  //挂载替换好模板的节点
  const oFrag = document.createDocumentFragment();

  // console.log(domNodePool); -> [ul.list, ul.list]
  domNodePool.forEach(node => {
    oFrag.appendChild(node);
  });

  /**
   * console.log(oFrag);
   * #document-fragment
   *   <ul class="list">...</ul>
   *   <ul class="list">...</ul>
   */

  //挂载到app 渲染到浏览器页面
  app.appendChild(oFrag);

}